<script lang="ts" setup>
import {reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {User, Lock, Iphone} from '@element-plus/icons-vue'
import type {FormInstance, FormRules} from 'element-plus'
import Fitness from "@/components/icons/Fitness.vue";
import type {RegisterInfo} from "@/type/member.ts";
import {registerMember} from "@/api/member";
import {useRouter} from "vue-router";

const ruleFormRef = ref<FormInstance>()

const checkInput = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('不可为空,请输入...'))
  } else {
    callback()
  }
}

const validateUsername = (rule: any, value: any, callback: any) => {
  if (/^\d+$/.test(value)) {
    callback(new Error('用户名不能纯数字'))
  } else {
    callback()
  }
}

const validatePassword = (rule: any, value: any, callback: any) => {
  if (/^\d+$/.test(value)) {
    callback(new Error('密码不能纯数字'))
  } else if (value.length < 6) {
    callback(new Error('密码长度至少为6位'))
  } else {
    if (registerForm.checkPassword !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPassword')
    }
    callback()
  }
}

const validateCheckPassword = (rule: any, value: any, callback: any) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致!'))
  } else {
    callback()
  }
}

const validatePhone = (rule: any, value: any, callback: any) => {
  if (value && !/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入有效的中国大陆手机号'))
  } else {
    callback()
  }
}

const checkAge = (rule: any, value: any, callback: any) => {
  if (!value) return callback()
  setTimeout(() => {
    if (!Number.isInteger(value)) {
      callback(new Error('请输入数字'))
    } else {
      if (value < 8 || value > 75) {
        callback(new Error('年龄不符'))
      } else {
        callback()
      }
    }
  }, 500)
}

const registerForm = reactive({
  username: '',
  memberName: '',
  password: '',
  checkPassword: '',
  age: undefined,
  gender: '',
  phone: '',
})

const rules = reactive<FormRules>({
  username: [
    {validator: checkInput, trigger: 'blur'},
    {validator: validateUsername, trigger: 'blur'}
  ],
  memberName: [{validator: checkInput, trigger: 'blur'}],
  password: [
    {validator: checkInput, trigger: 'blur'},
    {validator: validatePassword, trigger: 'blur'}
  ],
  checkPassword: [
    {validator: checkInput, trigger: 'blur'},
    {validator: validateCheckPassword, trigger: 'blur'}
  ],
  phone: [
    {validator: checkInput, trigger: 'blur'},
    {validator: validatePhone, trigger: 'blur'}
  ],
  age: [{validator: checkAge, trigger: 'blur'}],
  gender: [],
  address: [],
})

const router = useRouter()

const register = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      const registerInfo: RegisterInfo = {
        username: registerForm.username,
        memberName: registerForm.memberName,
        password: registerForm.password,
        age: registerForm.age,
        gender: registerForm.gender,
        contact: registerForm.phone
      }
      const result = await registerMember(registerInfo)
      if (result.code == 1) {
        ElMessage.success('注册成功')
        await router.push('/memberLogin')
      } else {
        ElMessage.error('注册失败，请稍后重试……')
      }
    } else {
      ElMessage.error('请检查输入')
    }
  })
}
</script>

<template>
  <div class="register-container">
    <div class="register-main">
      <div class="header">
        <Fitness style="--icon-size: 1.2em"/>
        加入健身中心
      </div>
      <div class="register-form">
        <el-form ref="ruleFormRef" :inline-message="true" :model="registerForm" :rules="rules" label-width="auto"
                 status-icon style="max-width: 600px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="registerForm.username" :prefix-icon="User" placeholder="请输入用户名"/>
              </el-form-item>
              <el-form-item label="姓名" prop="memberName">
                <el-input v-model="registerForm.memberName" :prefix-icon="User" placeholder="请输入姓名"/>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="registerForm.password" :prefix-icon="Lock" placeholder="请输入密码" show-password
                          type="password"/>
              </el-form-item>
              <el-form-item label="确认密码" prop="checkPassword">
                <el-input v-model="registerForm.checkPassword" :prefix-icon="Lock" placeholder="请再次输入密码"
                          show-password
                          type="password"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="registerForm.phone" :prefix-icon="Iphone" placeholder="请输入手机号"/>
              </el-form-item>
              <el-form-item label="年龄" prop="age">
                <el-input v-model="registerForm.age" placeholder="请输入年龄"/>
              </el-form-item>
              <el-form-item label="性别" prop="gender">
                <el-select v-model="registerForm.gender" placeholder="请选择性别">
                  <el-option label="男" value="male"/>
                  <el-option label="女" value="female"/>
                  <el-option label="不填" value=""/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <div class="register-button-container">
              <el-button class="register-button" color="#93ccc9" @click="register(ruleFormRef)">
                注册
              </el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="to-login">
              已有账号？去
              <RouterLink to="/memberLogin">登录</RouterLink>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: linear-gradient(to right, #c2e59c, #64b3f4);

  .register-main {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    width: 600px; // 增加宽度以适应双列布局
    text-align: center;

    .header {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 38px;
      font-weight: bold;
      //text-align: center;
      line-height: 180px; // 调整行高
    }

    .register-form {
      padding: 0 20px;

      .el-row {
        display: flex;
        justify-content: space-between;
      }

      .el-col {
        width: 48%; // 调整列宽
      }

      .register-button-container {
        display: flex;
        justify-content: center;
        width: 100%;
        padding-top: 15px;

        .register-button {
          width: 50%;
          border-radius: 5px;
        }
      }

      .to-login {
        display: flex;
        justify-content: center;
        align-items: center;
        padding-top: 20px;
        width: 100%;
      }
    }
  }
}
</style>
